from machine import ADC, Pin

class Battery():
    
    VOLTAGE_LEVEL = [3.27, 3.61, 3.69, 3.71, 3.73, 3.75, 3.77, 3.79, 3.80, 3.82, 3.84, 3.85, 3.87, 3.91, 3.95, 3.98, 4.02, 4.08, 4.11, 4.15, 4.20]
    R1 = 33.0
    R2 = 120.0
    VOLTAGE_DIVIDE = R1 / (R1+R2)
    
    def __init__(self, pin):
        self.adc = ADC(Pin(pin))            # create ADC object on ADC pin
    
    def get_raw(self):
        return self.adc.read()
    
    def raw2voltate(self, raw):
        voltage = raw / 1023.0
        voltage = round(voltage / self.VOLTAGE_DIVIDE, 2)
        return voltage
        
    def voltage2level(self, voltage):
        for i, vs in enumerate(self.VOLTAGE_LEVEL):
            if voltage < vs:
                level = i * 5
                break
        else:
            level = 100
        return level
        
    def get_voltage(self):
        val = self.get_raw()
        return self.raw2voltate(val)
    
    def get_level(self):
        voltage = self.get_voltage()
        return self.voltage2level(voltage)
        

